<?php

namespace app\api\controller\free;

use addons\alioss\Alioss;
use app\admin\model\free\Config as ActivityConfig;
use app\admin\model\free\Coupon;
use app\admin\model\free\Seckill;
use app\admin\model\User;
use app\common\controller\Api;
use think\Exception;

/**
 * 活动接口
 */
class Activity extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function activityInfo(){
        $activityConfig = ActivityConfig::find();
        // 获取oss地址
        $config = (new Alioss()) ->getConfig();
        $oss_url = $config['cdnurl'];
        if($oss_url) {
            $activityConfig['new_user_bg'] = $oss_url . $activityConfig['new_user_bg'];
            $activityConfig['join_group_bg'] = $oss_url . $activityConfig['join_group_bg'];
            $activityConfig['join_group_bg2'] = $oss_url . $activityConfig['join_group_bg2'];
            $activityConfig['seckill_bg'] = $oss_url . $activityConfig['seckill_bg'];
            $activityConfig['group_code_image'] = $oss_url . $activityConfig['group_code_image'];
        }

        $this->success('ok',$activityConfig);
    }

    private function getTodaySeckillInfo()
    {
        $todayStart = strtotime('today');
        $todayEnd = strtotime('tomorrow') - 1;
        $seckillInfo = Seckill::where('seckill_start_time', '>=', $todayStart)
            ->where('seckill_end_time', '<=', $todayEnd)
            ->find();

        if (!$seckillInfo) {
            // 获取活动配置
            $activityConfig = ActivityConfig::find();

            if ($activityConfig && $activityConfig['status'] == 'start') {
                // 创建今日秒杀活动
                $newSeckill = [
                    'coupon_quantity' => $activityConfig['coupon_quantity'],
                    'coupon_remain_quantity' => $activityConfig['coupon_quantity'],
                    'coupon_effective_time' => $activityConfig['seckill_coupon_effective_time'],
                    'seckill_start_time' => strtotime(date('Y-m-d') . ' ' . date('H:i:s', $activityConfig['seckill_start_time'])),
                    'seckill_end_time' => strtotime(date('Y-m-d') . ' ' . date('H:i:s', $activityConfig['seckill_end_time'])),
                ];
                $seckillInfo = Seckill::create($newSeckill);

            }
        }
        return $seckillInfo;
    }

    /**
     * 获取秒杀活动信息
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function seckillInfo()
    {

//        $date1 = $this->request->post('date');
//        $date2 = date('Y-m-d');
//
//        if(!$date1 != $date2){
//            $this->error('链接已过期');
//        }
        // 获取今日秒杀活动信息
        $seckillInfo = $this->getTodaySeckillInfo();
        if (!$seckillInfo) {
            $this->error('今日没有活动');
        }

        $this->success('成功', $seckillInfo);
    }


    /**
     * 参与秒杀活动
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function seckill()
    {

        $date1 = $this->request->post('date');
        $date2 = date('Y-m-d');


        if($date1 != $date2){
            $this->error('链接已过期');
        }


        // 获取今日秒杀活动信息
        $seckillInfo = $this->getTodaySeckillInfo();
        if (!$seckillInfo) {
            $this->error('今日没有活动');
        }

        if ($seckillInfo['coupon_remain_quantity'] <= 0) {
            $this->error('活动已结束');
        }

        // 查询用户是否参与过秒杀
        $where = [
            'user_id' => ['=', $this->auth->id],
            'source_type' => ['=', 'seckill'],
            'source_id' => ['=', $seckillInfo['id']],
        ];
        $coupon = Coupon::where($where)->find();

        if ($coupon) {
            $this->error('您今天已经参与过活动');
        } else {
            // 更新秒杀活动剩余数量
            try {
                Seckill::where([
                    'id' => ['=', $seckillInfo['id']],
                    'coupon_remain_quantity' => ['>', 0]
                ])->setDec('coupon_remain_quantity');
            } catch (Exception $e) {
                $this->error('活动已结束');
            }
            // 创建优惠券
            $coupon = Coupon::create([
                'user_id' => $this->auth->id,
                'name' => '限时福利免单券',
                'source_type' => 'seckill',
                'source_id' => $seckillInfo['id'],
                'expiration_time' => time() + $seckillInfo['coupon_effective_time'] * 3600,
            ]);

            $this->success('成功');
        }
    }


    /**
     * 新用户领免单券
     * @return void
     */
    public function newUserCoupon(){

        $coupon = Coupon::where([
            'user_id' => ['=', $this->auth->id],
            'source_type' => ['=', 'register'],
        ])->find();

        if ($coupon) {
            $this->error('您已经领取过新用户免单券');
        }else {

            $user = $this->auth->getUserinfo();
            $activityConfig = ActivityConfig::find();
            // 用户注册时间大于活动创建时间
            if ($user['free_acive_type'] != 0) {
                $this->error('您不符合活动条件');
            }else {
                Coupon::create([
                    'user_id' => $this->auth->id,
                    'name' => '新用户福利免单券',
                    'source_type' => 'register',
                    'expiration_time' => time() + $activityConfig['new_user_coupon_effective_time'] * 3600,
                ]);

                User::update(['free_acive_type'=>1],['id'=>$this->auth->id]);

                $this->success('成功');
            }

        }

    }

    /**
     * 领加群免单券
     * @return void
     */
    public function joinGroupCoupon(){

        $coupon = Coupon::where([
            'user_id' => ['=', $this->auth->id],
            'source_type' => ['=', 'group'],
        ])->find();

        if ($coupon) {
            $this->error('您已经领取过加群免单券');
        }else {
            $user = $this->auth->getUserinfo();
            $activityConfig = ActivityConfig::find();
            // 用户注册时间大于活动创建时间
            if ($user['free_acive_type'] == 2) {
                $this->error('您不符合活动条件');
            }else {
                Coupon::create([
                    'user_id' => $this->auth->id,
                    'name' => '加群福利免单券',
                    'source_type' => 'group',
                    'expiration_time' => time() + $activityConfig['join_group_coupon_effective_time'] * 3600,
                ]);
//                User::update(['free_acive_type'=>2],['id'=>$this->auth->id]);

                $this->success('成功');
            }

        }

    }


    /**
     * 免单券列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function couponList(){

        $status = $this->request->post('status');
        $where = [
            'user_id' => ['=', $this->auth->id]
        ];
        if ($status) {
            $where['status'] = ['=', $status];
        }
        // 更新免单券失效状态
        Coupon::update(['status' => 'expired'],[
//            'user_id' => ['=', $this->auth->id],
            'status' => ['=', 'created'],
            'expiration_time' => ['<', time()]
        ]);

        $list = Coupon::where($where)->order('expiration_time','asc')->select();

        $this->success('成功', $list);
    }



}
